<template>
  <div class="user-management">
    <t-card title="用户账号管理">
      <div class="search-bar">
        <t-input v-model="searchName" placeholder="搜索姓名" class="search-input" />
        <t-input v-model="searchUserNo" placeholder="搜索编号" class="search-input" />
        <el-button color="#409CFB" @click="searchUsers" theme="primary" icon="search" class="search-button">搜索</el-button>
        <el-button color="#409CFB" @click="openAddUserDialog" theme="primary" icon="add" class="add-button">添加用户</el-button>
      </div>
      <div class="table-container">
        <t-table :data="users" :columns="columns" :loading="loading" row-key="userId" class="user-table">
          <template #name="{ row }">
            <span>{{ row.name }}</span>
          </template>
          <template #gender="{ row }">
            <span>{{ row.gender }}</span>
          </template>
          <template #type="{ row }">
            <span>{{ row.type }}</span>
          </template>
          <template #grade="{ row }">
            <span>{{ row.grade }}</span>
          </template>
          <template #dormGroup="{ row }">
            <span>{{ row.dormGroup }}</span>
          </template>
          <template #dormBuilding="{ row }">
            <span>{{ row.dormBuilding }}</span>
          </template>
          <template #dormRoom="{ row }">
            <span>{{ row.dormRoom }}</span>
          </template>
          <template #actions="{ row }">
            <el-button theme="primary" @click="openEditUserDialog(row)" class="action-button">修改</el-button>
            <el-button theme="danger" @click="deleteUser(row.userId)" class="action-button">移除</el-button>
          </template>
        </t-table>
      </div>
      <div class="pagination-container">
        <t-pagination
            v-model:current="page"
            v-model:pageSize="pageSize"
            :total="total"
            @change="fetchUsers"
            class="pagination"
        />
      </div>
    </t-card>

    <!-- 添加/修改用户对话框 -->
    <t-dialog :visible.sync="userDialogVisible" :title="dialogTitle" width="500px">
      <t-form :model="userForm" :rules="rules" ref="userFormRef" @submit.prevent="handleUserDialogConfirm">
        <t-form-item label="用户编号" name="userNo">
          <t-input v-model="userForm.userNo" />
        </t-form-item>
        <t-form-item label="姓名" name="name">
          <t-input v-model="userForm.name" />
        </t-form-item>
        <t-form-item label="性别" name="gender">
          <t-select v-model="userForm.gender">
            <t-option value="男">男</t-option>
            <t-option value="女">女</t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="用户类型" name="type">
          <t-input v-model="userForm.type" />
        </t-form-item>
        <t-form-item label="年级" name="grade">
          <t-input v-model="userForm.grade" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="userForm.email" />
        </t-form-item>
        <t-form-item label="密码" name="password">
          <t-input type="password" v-model="userForm.password" />
        </t-form-item>
        <t-form-item label="宿舍组团" name="dormGroup">
          <t-select v-model="userForm.dormGroup">
            <t-option value="一号组团">一号组团</t-option>
            <t-option value="二号组团">二号组团</t-option>
            <t-option value="三号组团">三号组团</t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="宿舍楼栋" name="dormBuilding">
          <t-select v-model="userForm.dormBuilding">
            <t-option v-for="i in 30" :key="i" :value="'#' + i">{{ '#' + i }}</t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="宿舍号" name="dormRoom">
          <t-input v-model="userForm.dormRoom" />
        </t-form-item>
        <t-form-item label="创建时间" name="createTime">
          <t-date-picker v-model="userForm.createTime" format="YYYY-MM-DD HH:mm:ss" />
        </t-form-item>
        <t-form-item label="更新时间" name="updateTime">
          <t-date-picker v-model="userForm.updateTime" format="YYYY-MM-DD HH:mm:ss" />
        </t-form-item>
        <div class="dialog-footer">
          <t-button theme="default" @click="handleDialogCancel">取消</t-button>
          <t-button theme="primary" @click="handleUserDialogConfirm">确认</t-button>
        </div>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const searchName = ref('');
const searchUserNo = ref('');  // 新增的搜索编号输入框绑定变量
const users = ref([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const userDialogVisible = ref(false);
const dialogTitle = ref('');
const userFormRef = ref(null);
const userForm = reactive({
  userNo: '',
  name: '',
  gender: '',
  type: '',
  grade: '',
  email: '',
  password: '',
  dormGroup: '',
  dormBuilding: '',
  dormRoom: '',
  createTime: '',
  updateTime: '',
});
const originalUserForm = reactive({ ...userForm }); // 保存原始的用户表单数据
const rules = {
  userNo: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  email: [{ required: true, type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
};

const columns = [
  { title: '用户编号', colKey: 'userNo', width: 150 },
  { title: '姓名', colKey: 'name', slot: 'name' },
  { title: '性别', colKey: 'gender', slot: 'gender' },
  { title: '用户类型', colKey: 'type', slot: 'type' },
  { title: '年级', colKey: 'grade', slot: 'grade' },
  { title: '宿舍组团', colKey: 'dormGroup', slot: 'dormGroup' },
  { title: '宿舍楼栋', colKey: 'dormBuilding', slot: 'dormBuilding' },
  { title: '宿舍号', colKey: 'dormRoom', slot: 'dormRoom' },
  { title: '操作', colKey: 'actions', slot: 'actions' },
];

const fetchUsers = async () => {
  loading.value = true;
  try {
    const response = await axios.post('/api/users/listUsersPage1', {
      pageNum: page.value,
      pageSize: pageSize.value,
      param: {
        name: searchName.value,
        userNo: searchUserNo.value,
      }
    });
    users.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败');
  } finally {
    loading.value = false;
  }
};

const searchUsers = () => {
  page.value = 1;
  fetchUsers();
};

const deleteUser = async (userId) => {
  const confirm = window.confirm('确定删除该用户吗？');
  if (confirm) {
    try {
      await axios.get(`/api/users/delete?user_id=${userId}`);
      fetchUsers();
      ElMessage.success('用户移除成功');
    } catch (error) {
      console.error('移除用户失败:', error);
      ElMessage.error('移除用户失败');
    }
  }
};

const handleUserDialogConfirm = async () => {
  userFormRef.value.validate().then(async () => {
    try {
      const isModified = Object.keys(userForm).some(key => userForm[key] !== originalUserForm[key]);
      if (!isModified) {
        ElMessage.info('没有修改任何信息');
        return;
      }
      const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
      if (!userForm.createTime) userForm.createTime = currentTime;
      if (!userForm.updateTime) userForm.updateTime = currentTime;
      if (dialogTitle.value === '添加用户') {
        await axios.post('http://localhost:8000/users/add', userForm);
      } else {
        await axios.post('http://localhost:8000/users/update', userForm);
      }
      fetchUsers();
      ElMessage.success(`${dialogTitle.value}成功`);
      userDialogVisible.value = false;
    } catch (error) {
      console.error('处理用户对话框失败:', error);
      ElMessage.error(`${dialogTitle.value}失败`);
    }
  });
};

const handleDialogCancel = () => {
  userDialogVisible.value = false;
};

const openAddUserDialog = () => {
  dialogTitle.value = '添加用户';
  Object.assign(userForm, {
    userNo: '',
    name: '',
    gender: '',
    type: '',
    grade: '',
    email: '',
    password: '',
    dormGroup: '',
    dormBuilding: '',
    dormRoom: '',
    createTime: '',
    updateTime: '',
  });
  Object.assign(originalUserForm, { ...userForm });
  userDialogVisible.value = true;
};

const openEditUserDialog = (row) => {
  dialogTitle.value = '修改用户';
  Object.assign(userForm, row);
  Object.assign(originalUserForm, { ...row });
  userDialogVisible.value = true;
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

.search-button, .add-button {
  height: 32px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.action-button {
  margin-right: 10px;
}
</style>
